import 'dart:async';

import 'package:device_info/device_info.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_oldman_health/api/auth_service.dart';
import 'package:flutter_oldman_health/models/response_data_model.dart';
import 'package:flutter_oldman_health/pages/setting/user_agreement_page.dart';
import 'package:flutter_oldman_health/utils/utils.dart';
import 'package:flutter_oldman_health/widget/common_container.dart';

class RegisterPage extends StatefulWidget {
  @override
  _RegisterPageState createState() {
    return _RegisterPageState();
  }
}

class _RegisterPageState extends State<RegisterPage> {
  final TextEditingController _controllerName = TextEditingController();
  final TextEditingController _controllerPhone = TextEditingController();
  final TextEditingController _controllerPsw = TextEditingController();
  final TextEditingController _controllerPsw2 = TextEditingController();
  final TextEditingController _controllerCode = TextEditingController();

  String textCodeButton = "获取验证码";
  int countdownTime = 0;
  bool waitingCode = false;
  bool userAgreement = false;
  Timer _timer;

  Color normalColor = Color(0xff41BAB0);
  Color activeColor = Color(0xFFdddddd);

  @override
  void dispose() {
    super.dispose();
    if (_timer != null) {
      _timer.cancel();
    }
  }

  startCountdown() {
    countdownTime = 59;
    final call = (timer) {
      setState(() {
        if (countdownTime < 1) {
          _timer.cancel();
          waitingCode = false;
          textCodeButton = "获取验证码";
        } else {
          countdownTime -= 1;
          textCodeButton = "${countdownTime}s后重新获得";
        }
      });
    };
    _timer = Timer.periodic(Duration(seconds: 1), call);
  }

  @override
  void initState() {
    super.initState();
    //deviceInfo();

    new Future.delayed(new Duration(seconds: 3), () {
      return 1;
    })
        .timeout(new Duration(seconds: 2))
        .then((value) => print)
        .catchError(print)
        .whenComplete(() => print);
  }

  void deviceInfo() async {
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    //AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
    IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
    print('Running on ${iosInfo.utsname.machine}'); //  identifierForVendor
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: true,
        body: Container(
          //padding: EdgeInsets.only(top: 12),
            color: Colors.white,
            child: SingleChildScrollView(
                child: Column(
                  // verticalDirection:VerticalDirection.down,
                  // mainAxisAlignment: MainAxisAlignment.start,
                  // crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      _getTitle(),
                      CommonContainer(Row(children: [
                        Text("姓名:  ", style: TextStyle(fontSize: 18)),
                        Expanded(
                            flex: 1,
                            child: TextField(
                                controller: _controllerName,
                                maxLines: 1,
                                autofocus: true,
                                inputFormatters: [
                                  LengthLimitingTextInputFormatter(6)
                                ],
                                style: TextStyle(
                                    fontSize: 18,
                                    color: Colors.black87,
                                    fontWeight: FontWeight.w300),
                                // obscureText: true,
                                decoration: getInputDecoration("请输入您的姓名")))
                      ])),
                      CommonContainer(
                          Row(children: [
                            Text("手机号:  ", style: TextStyle(fontSize: 18)),
                            Expanded(
                                flex: 1,
                                child: TextField(
                                    inputFormatters: [
                                      LengthLimitingTextInputFormatter(11),
                                      FilteringTextInputFormatter.digitsOnly
                                    ],
                                    keyboardType: TextInputType.number,
                                    controller: _controllerPhone,
                                    maxLines: 1,
                                    autofocus: true,
                                    style: TextStyle(
                                        fontSize: 18,
                                        color: Colors.black87,
                                        fontWeight: FontWeight.w300),
                                    // obscureText: true,
                                    decoration: getInputDecoration("请输入手机号")))
                          ]),
                          margin: EdgeInsets.fromLTRB(20, 0, 20, 20)),
                      CommonContainer(
                          Row(children: [
                            Text("密码:  ", style: TextStyle(fontSize: 18)),
                            Expanded(
                                flex: 1,
                                child: TextField(
                                    obscureText: true,
                                    controller: _controllerPsw,
                                    maxLines: 1,
                                    autofocus: true,
                                    inputFormatters: [
                                      LengthLimitingTextInputFormatter(12)
                                    ],
                                    style: TextStyle(
                                        fontSize: 18,
                                        color: Colors.black87,
                                        fontWeight: FontWeight.w300),
                                    // obscureText: true,
                                    decoration: getInputDecoration("请输入密码")))
                          ]),
                          margin: EdgeInsets.fromLTRB(20, 0, 20, 20)),
                      CommonContainer(
                          Row(children: [
                            Text("密码:  ", style: TextStyle(fontSize: 18)),
                            Expanded(
                                flex: 1,
                                child: TextField(
                                    obscureText: true,
                                    controller: _controllerPsw2,
                                    maxLines: 1,
                                    autofocus: true,
                                    inputFormatters: [
                                      LengthLimitingTextInputFormatter(12)
                                    ],
                                    style: TextStyle(
                                        fontSize: 18,
                                        color: Colors.black87,
                                        fontWeight: FontWeight.w300),
                                    // obscureText: true,
                                    decoration: getInputDecoration("请再次输入密码")))
                          ]),
                          margin: EdgeInsets.fromLTRB(20, 0, 20, 20)),
                      Row(
                        children: [
                          Expanded(
                              flex: 1,
                              child: CommonContainer(
                                  TextField(
                                      controller: _controllerCode,
                                      maxLines: 1,
                                      inputFormatters: [
                                        LengthLimitingTextInputFormatter(4),
                                        FilteringTextInputFormatter.digitsOnly
                                      ],
                                      keyboardType: TextInputType.number,
                                      autofocus: true,
                                      style: TextStyle(
                                          fontSize: 18,
                                          color: Colors.black87,
                                          fontWeight: FontWeight.w300),
                                      // obscureText: true,
                                      decoration: getInputDecoration("请输入验证码")),
                                  margin: EdgeInsets.fromLTRB(20, 0, 10, 0))),
                          CommonContainer(
                              GestureDetector(
                                behavior: HitTestBehavior.translucent,
                                onTap: () async {
                                  print(textCodeButton);
                                  if (_controllerPhone.text == null ||
                                      !Utils.phoneStr(_controllerPhone.text)||
                                      _controllerPhone.text.length != 11) {
                                    EasyLoading.showInfo("手机号码输入有误");
                                    return;
                                  }
                                  if (textCodeButton.length != 5) {
                                    return;
                                  }

                                  var response =
                                  await AuthService.requestVerificationCode(
                                      _controllerPhone.text);
                                  if (response != null &&
                                      response.statusCode == 200) {
                                    EasyLoading.showSuccess('获取验证码成功');

                                    ResponseDataModel<String> value =
                                    ResponseDataModel<String>.fromJson(
                                        response.data);
                                    if (value.success()) {
                                      setState(() {
                                        waitingCode = true;
                                        textCodeButton = "59s后重新获得";
                                      });
                                      startCountdown();
                                    } else {
                                      EasyLoading.showInfo(value.msg);
                                    }
                                  }

                                  // ResponseDataModel<String> value =
                                  //     await UserDao.requestVerificationCode(
                                  //         textEditPhone);
                                },
                                child: Text(textCodeButton,
                                    style: TextStyle(
                                        fontSize: 18,
                                        color: waitingCode
                                            ? activeColor
                                            : normalColor)),
                              ),
                              margin: EdgeInsets.only(right: 20),
                              padding: EdgeInsets.all(16))
                        ],
                      ),
                      Row(children: [
                        Container(
                            child: Checkbox(
                                shape: CircleBorder(),
                                onChanged: (v) {
                                  userAgreement = !userAgreement;
                                  setState(() {});
                                },
                                value: userAgreement),
                            padding: EdgeInsets.only(left: 10)),
                        Text(
                            "已阅读同意", style: TextStyle(color: Colors.grey[600])),
                        GestureDetector(onTap:(){
                          Navigator.push(context,
                              MaterialPageRoute(builder: (context) => UserAgreementPage()));
                        }, child: Text(
                          "用户协议和隐私条款",
                          style: TextStyle(
                              color: Colors.blue,
                              decoration: TextDecoration.underline),
                        ))
                      ]),
                      Container(
                          margin: EdgeInsets.fromLTRB(20, 40, 20, 0),
                          padding: EdgeInsets.all(16),
                          child: GestureDetector(
                              behavior: HitTestBehavior.translucent,
                              onTap: () async {
                                if (!userAgreement) {
                                  EasyLoading.showInfo("未勾选用户协议");
                                  return;
                                }
                                if (_controllerName.text == null ||
                                    _controllerName.text.length == 0) {
                                  EasyLoading.showInfo("请填写姓名");
                                  return;
                                }
                                if (_controllerPhone.text == null ||
                                    !Utils.phoneStr(_controllerPhone.text)||
                                    _controllerPhone.text.length != 11) {
                                  EasyLoading.showInfo("手机号码输入有误");
                                  return;
                                }
                                if (_controllerPsw.text == null ||
                                    _controllerPsw2.text == null) {
                                  EasyLoading.showInfo("请填写密码");
                                  return;
                                }
                                if (_controllerPsw.text.length < 6) {
                                  EasyLoading.showInfo("密码至少6位");
                                  return;
                                }
                                if (_controllerPsw.text !=
                                    _controllerPsw2.text) {
                                  EasyLoading.showInfo("两次密码不一致");
                                  return;
                                }
                                if (_controllerCode.text == null ||
                                    _controllerCode.text.length < 4) {
                                  EasyLoading.showInfo("请填写验证码");
                                  return;
                                }
                                var response = await AuthService.register(
                                    _controllerName.text,
                                    _controllerPhone.text,
                                    _controllerPsw.text,
                                    _controllerCode.text);
                                if (response != null &&
                                    response.statusCode == 200) {
                                  ResponseDataModel<String> value1 =
                                  ResponseDataModel.fromJson(response.data);
                                  if (value1.success()) {
                                    AuthService.login2(
                                        context,
                                        _controllerPhone.text,
                                        _controllerPsw.text,
                                        "注册成功",
                                        true);
                                    _timer.cancel();
                                  } else {
                                    EasyLoading.showInfo(value1.msg);
                                  }
                                }
                              },
                              child: FractionallySizedBox(
                                  widthFactor: 1,
                                  child: Text("注册",
                                      textAlign: TextAlign.center,
                                      style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          fontSize: 18,
                                          color: Colors.white)))),
                          decoration: BoxDecoration(
                              border:
                              Border.all(color: Color(0xFFEEEEEE), width: 1),
                              color: Color(0xff41BAB0),
                              borderRadius: BorderRadius.all(
                                  Radius.circular(58))))
                    ]))));
  }

  InputDecoration getInputDecoration(String hintText) {
    return InputDecoration(
        fillColor: Colors.red,
        hintText: hintText,
        hintStyle: TextStyle(fontSize: 18),
        //InputBorder.none  OutlineInputBorder()
        border: InputBorder.none);
  }

  Widget _getTitle([String title = "注册"]) {
    return Container(
      //color: Colors.white,
        padding: EdgeInsets.fromLTRB(16, 46, 16, 0),
        child: FractionallySizedBox(
          widthFactor: 1,
          child: Stack(
            alignment: Alignment.center,
            children: [
              Positioned(
                  left: 2,
                  top: 5,
                  child: GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: () {
                        Navigator.pop(context);
                      },
                      child: Container(
                          child: Icon(Icons.arrow_back_ios),
                          padding: EdgeInsets.fromLTRB(15, 0, 20, 10)))),
              Text(title,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      fontSize: 22,
                      color: Colors.black87,
                      fontWeight: FontWeight.normal)),
            ],
          ),
        ));
  }
}
